#include "PrecompiledHeaders.h"
#include "CameraControl.h"

/*
 * Create the cameras and initialise all variables
 */
CameraControl::CameraControl(Ogre::Viewport *m_v, Ogre::Viewport *l_v,
    Ogre::Viewport *r_v, Ogre::SceneManager *sm, Ogre::String prefix)
{
    player = NULL;
    yaw = 0;
    main_node = NULL;
    main_camera = sm->createCamera(prefix + "main_camera");
    main_camera->setAspectRatio(Ogre::Real(m_v->getActualWidth()) / Ogre::Real(m_v->getActualHeight()));
    if(l_v) {
        left_camera = sm->createCamera(prefix + "left_camera");
        left_camera->setAspectRatio(Ogre::Real(l_v->getActualWidth()) / Ogre::Real(l_v->getActualHeight()));
    }
    else left_camera = NULL;
    if(r_v) {
        right_camera = sm->createCamera(prefix + "right_camera");
        right_camera->setAspectRatio(Ogre::Real(r_v->getActualWidth()) / Ogre::Real(r_v->getActualHeight()));
    }
    else right_camera = NULL;
    main_viewport = m_v;
    left_viewport = l_v;
    right_viewport = r_v;
    original_pitch = Ogre::Radian(0);
}

/*
 * Unregister the player from this camera and unattach the cameras from the
 * scene node
 */
void CameraControl::unregisterPlayer()
{
     player = NULL;
     if(main_node) main_node->detachAllObjects();
}

/*
 * Get the rotation needed for the skybox to make it look like the level is
 * tilting
 */
Ogre::Quaternion CameraControl::getSkyOrientation()
{
    Ogre::Quaternion result(-roll, main_camera->getRealDirection());
    return result * Ogre::Quaternion(pitch, main_camera->getRealRight());
}

/*
 * Reset the camera's orientation. Position is reset when players position is
 * reset because the camera is a child of the player in Ogre
 */
void CameraControl::reset()
{
    main_node->resetOrientation();
}
void CameraControl::rotate(Ogre::Radian y)
{
    yaw += y;
    main_node->roll(-roll);
    main_node->pitch(-pitch - (extra_pitch * (1 - previous_scale)));
    main_node->yaw(y);
    main_node->pitch(pitch + (extra_pitch * (1 - previous_scale)));
    main_node->roll(roll);
}
